import java.io.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static java.lang.System.out;

public class  MobileClient {
    String uname;
    PrintWriter printWriter;
    BufferedReader bufferReader;
    Socket client;
    MessagesThread myThread;

    public MobileClient(String uname,String servername) throws Exception {
        this.uname = uname;
        client  = new Socket(servername,2046);
        bufferReader = new BufferedReader( new InputStreamReader( client.getInputStream()) ) ;
        printWriter = new PrintWriter(client.getOutputStream(),true);
        printWriter.println( "mobile " + uname );  // send name to server
        myThread = new MessagesThread();
        myThread.start();  // create thread for listening for messages
    }


    public static void main(String ... args) {
      System.out.print("User Name: ");
        Scanner stdin = new Scanner( System.in );
        // take username from user
        String name = stdin.nextLine();
        System.out.println("Connecting...");
        String servername = "lore.cs.purdue.edu";
        try {
            new MobileClient( name ,servername);
        } catch(Exception ex) {
            out.println( "Error --> " + ex.getMessage());
        }

    } // end of main

    // Check if myThread is alive
    public boolean isAlive()
    {
    	return myThread.isAlive();
    }
    
    // Terminate the mobile client thread
    public void terminate()
    {
    	myThread.terminate();
    	printWriter.println("QUIT");
    }
    
    // inner class for Messages Thread
    class  MessagesThread extends Thread {
    	 private volatile Boolean ifStop = false;
         
         // Function to terminate the current thread
         public void terminate() {
             ifStop = true;
         }
        public void run() {
            String line;
            Thread thisThread = Thread.currentThread();
            try {
                while(ifStop==false) {
                    Scanner stdin = new Scanner( System.in );
                    String mymsg = stdin.nextLine();
                     printWriter.println( mymsg );
                } // end of while
            } catch(Exception ex) {}
            return;
        }
    }
} //  end of client
